﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Atlandiz.Data;
using Microsoft.SqlServer.Management.Smo;
using System.IO;

namespace Atlandiz.EnvanterVeZimmetYonetimi
{
    public partial class FormVeritabaniOlustur : DevExpress.XtraEditors.XtraForm
    {
        public FormVeritabaniOlustur()
        {
            InitializeComponent();
        }

        private void _btnKapat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void VeritabaniOlustur_Load(object sender, EventArgs e)
        {
            Army.EventConfirm = false;
        }

        public void GetSunucuListesi() {

            try
            {
                if (_txtSqlSunucuString.Properties.Items.Count == 0)
                {
                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                    MsSqlAccessLayer Sql = new MsSqlAccessLayer();
                    DataTable dt = Sql.GetServerList();

                    foreach (DataRow x in dt.Rows)
                    {
                        _txtSqlSunucuString.Properties.Items.Add(x["Name"].ToString());
                    }

                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Hata Oluştu", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void _txtSqlSunucuString_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            //GetSunucuListesi();
        }

        public MsSqlAccessLayer CheckSQLConnect(ref bool onError) {

            MsSqlAccessLayer newConnection = new MsSqlAccessLayer();
            try
            {
                switch (_cbUseTrustConnection.Checked) { 
                    case true:
                        MsSqlAccessLayer SqlforTrust = new MsSqlAccessLayer(_txtSqlSunucuString.Text, "master", true);
                        SqlforTrust.cmd("Select 1");
                        newConnection = SqlforTrust;
                        onError = false;
                        break;
                    case false:
                        MsSqlAccessLayer SqlforNonTrust = new MsSqlAccessLayer(_txtSqlSunucuString.Text, "master", _txtSqlKullaniciAdiString.Text, _txtSqlParolaString.Text);
                        SqlforNonTrust.cmd("Select 1");
                        newConnection = SqlforNonTrust;
                        onError = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                onError = true;
                MessageBox.Show(ex.Message.ToString(), "Bağlantı Hatası", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return newConnection;
        }

        private void _btnOlustur_Click(object sender, EventArgs e)
        {
            if (_txtSqlSunucuString.Text.Length<1)
            {
                MessageBox.Show("Sunucu Seçmeniz veya sunucu adresini yazmanız gerekir.", "Hata Oluştu", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _txtSqlSunucuString.Focus();
                return;
            }

            if (_txtSqlVeritabaniString.Text.Length < 1)
            {
                MessageBox.Show("Veritabanı Belirtmeniz gerekir.", "Hata Oluştu", MessageBoxButtons.OK, MessageBoxIcon.Information);
                _txtSqlVeritabaniString.Focus();
                return;
            }

            bool onError=true;
            MsSqlAccessLayer SQL = CheckSQLConnect(ref onError);

            if (onError==false)
            {

                switch (CheckVt(SQL)) { 
                    case true:
                        MessageBox.Show("Veritabanı zaten mevcut.\nTekrar oluşturamazsınız.", "Hata Oluştu", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    case false:
                        TablolariOlustur(SQL);
                        break;
                }
             }
        }

        public void TablolariOlustur(MsSqlAccessLayer Sql) {

            string filen = "";
            try
            {
                Sql.cmd("CREATE DATABASE " + _txtSqlVeritabaniString.Text);

                string[] filePaths = Directory.GetFiles(Application.StartupPath + "\\SQLFiles", "*.sql");
                foreach (string x in filePaths)
                {
                    FileInfo file = new FileInfo(x);
                    string script = file.OpenText().ReadToEnd();
                    script = script.Replace("@DATABASE", _txtSqlVeritabaniString.Text);
                    Sql.ExecuteSQLScript(script);
                    file.OpenText().Close();
                }

                Sql.cmd("USE [" + _txtSqlVeritabaniString.Text + "];INSERT INTO Kullanici (kAdi,Parola,AdSoyad,Yetki,isDeleted) VALUES('','9vntO4f7S5pzd8uNHeR8ypRwlMapx4xIKg4=','Admin',1,0)");
                Sql.cmd("USE [" + _txtSqlVeritabaniString.Text + "];INSERT INTO AppSettings (Uid,SettingKey,Value) VALUES(0,'VtVersion','1.20')");

                MessageBox.Show("Veritabanı: " + _txtSqlVeritabaniString.Text + "\nBaşarıyla oluşturuldu.", "İşlem Tamamlandı.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Army.NewVTName = _txtSqlVeritabaniString.Text;
                Army.NewVTServer = _txtSqlSunucuString.Text;
                Army.NewVTUsername = _txtSqlKullaniciAdiString.Text;
                Army.NewVTPassword = _txtSqlParolaString.Text;
                Army.NewVTTrustConnection = _cbUseTrustConnection.Checked;
                
                Army.EventConfirm = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString() + "\n" + filen, "Hata Oluştu", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool CheckVt(MsSqlAccessLayer Sql)
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            bool rt = false;
            DataTable dt = Sql.GetDataBases();
            foreach (DataRow x in dt.Rows) {
                if (x[0].ToString() == _txtSqlVeritabaniString.Text) rt = true;
            }
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            return rt;
        }

        private void _txtSqlSunucuString_QueryPopUp(object sender, CancelEventArgs e)
        {
            //GetSunucuListesi();
        }
    }
}